package com.chookss.home.knowledge;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.FileEntity;
import com.chookss.home.entity.FolderEntity;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.home.entity.KnowledgeTypeEntity;
import com.chookss.home.entity.UploadEntity;
import com.chookss.home.gallery.PublishGalleryActivity;
import com.chookss.home.knowledge.adaper.FolderAdapter;
import com.chookss.home.knowledge.adaper.JustOpenListAdapter;
import com.chookss.home.publish.PublishVedioActivity;
import com.chookss.home.tuwen.PublishTuwensActivity;
import com.chookss.mine.personal.upload.UploadFileService;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.filePicker.FilePicker;
import com.chookss.tools.filePicker.model.EssFile;
import com.chookss.tools.filePicker.util.Const;
import com.chookss.tools.filePicker.util.FileSizeUtil;
import com.chookss.tools.filePicker.util.FileUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.UploadBottomDialog;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

public class KnowledgeBaseSecondActivity extends BaseAct {

    public Context mContext;
    @BindView(R.id.topFlowLayout)
    RecyclerView titleRcv;
    @BindView(R.id.llLine2)
    View llLine2;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.folderRcv)
    RecyclerView folderRcv;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.rvType)
    RecyclerView rvType;
    @BindView(R.id.rlType)
    RelativeLayout rlType;
    @BindView(R.id.tvFolderName)
    TextView tvFolderName;
    @BindView(R.id.ivFolderArrow)
    ImageView ivFolderArrow;
    @BindView(R.id.llFolderArrow)
    LinearLayout llFolderArrow;
    @BindView(R.id.llFolder)
    LinearLayout llFolder;
    @BindView(R.id.tvFolderTopName)
    TextView tvFolderTopName;
    @BindView(R.id.llFolderTop)
    LinearLayout llFolderTop;
    @BindView(R.id.llFolderAll)
    LinearLayout llFolderAll;
    @BindView(R.id.tvFileName)
    TextView tvFileName;
    @BindView(R.id.ivFileArrow)
    ImageView ivFileArrow;
    @BindView(R.id.llFileArrow)
    LinearLayout llFileArrow;
    @BindView(R.id.llFile)
    LinearLayout llFile;
    @BindView(R.id.tvFileTopName)
    TextView tvFileTopName;
    @BindView(R.id.llFileTop)
    LinearLayout llFileTop;
    @BindView(R.id.llFileAll)
    LinearLayout llFileAll;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.fileRcv)
    RecyclerView fileRcv;
    @BindView(R.id.tvFileArrow)
    TextView tvFileArrow;
    @BindView(R.id.tvFolderArrow)
    TextView tvFolderArrow;
    @BindView(R.id.spaceView)
    View spaceView;
    @BindView(R.id.llChoose)
    LinearLayout llChoose;
    @BindView(R.id.llAdd)
    LinearLayout llAdd;

    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    //类型
    private TypeAdapter typeAdapter;
    private List<KnowledgeTypeEntity> typeEntityList = new ArrayList<>();
    //文件夹
    private List<FolderEntity> folderList = new ArrayList<>();
    private FolderAdapter folderAdapter;
    //文件
    private JustOpenListAdapter fileListAdapter;
    private List<FileEntity.ListBean> fileList = new ArrayList<>();
    //目录
    private TitleAdapter titleAdapter;
    private ArrayList<String> nameList = new ArrayList<>();//组织排列
    private String TAG = "KnowledgeBaseSecondActivity_DownloadFile";
    private int level = 1;//默认层级
    private String resourceType = "";////        资源类型（1资料，2长视频，3短视频4新闻5图文 6图片）
    private String resourceName = "";////        资源类型（1资料，2长视频，3短视频 4新闻5图文6图片）
    private String parentCode, folderNum;//上层级传下来的
    private boolean folderOpen = false, fileOpen = false;//默认都是关闭状态
    private String folderName = "", fileName = "";
    private String catalogCustomType = "";//自定义模块专用字段
    private String catalogType;//（0：全局 1: 题库 2:视频 3:资料库 4：图库 5：图文）
    private KnowledgeEntity levelOne;//一级目录数据
    private static final int REQUEST_CODE_CHOOSE = 23;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_knowledge_second);
        ButterKnife.bind(this);
        mContext = this;
        initState();

    }

    @Override
    public void initData() {
        level = getIntent().getIntExtra("level", 0);
        levelOne = (KnowledgeEntity) getIntent().getSerializableExtra("levelOne");
        ArrayList<String> nameLists = getIntent().getStringArrayListExtra("nameList");
        if (nameLists != null) {
            nameList.addAll(nameLists);
        }
        if (nameList.size() > 1) {
            resourceType = getIntent().getStringExtra("resourceType");
            tvTitle.setText(nameList.get(nameList.size() - 1));
            titleAdapter = new TitleAdapter(R.layout.item_folder_name_list, this, nameList);
            LinearLayoutManager lm = new LinearLayoutManager(this);
            lm.setOrientation(LinearLayoutManager.HORIZONTAL);
            titleRcv.setLayoutManager(lm);
            titleRcv.setAdapter(titleAdapter);
            titleRcv.setVisibility(View.VISIBLE);
            llLine2.setVisibility(View.VISIBLE);
        } else {
            if (levelOne != null) {
                resourceType = levelOne.getResourceType();
            }
            if (nameList.size() == 1) {
                tvTitle.setText(nameList.get(0));
            } else {
                tvTitle.setText("目录");
            }
        }
        parentCode = getIntent().getStringExtra("parentCode");
        folderNum = getIntent().getStringExtra("folderNum");
        catalogCustomType = getIntent().getStringExtra("catalogCustomType");
        catalogType = getIntent().getStringExtra("catalogType");
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getFileList();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getCatalogData();
                //定时器 倒计时
                Observable.timer(200, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) {
                                getFileList();
                            }
                        });
            }
        });
        KnowledgeTypeEntity knowledgeTypeEntity = new KnowledgeTypeEntity();
        knowledgeTypeEntity.setSelect(false);
        if (!Utils.isNull(resourceType)) {
            if (resourceType.equals("1,2,3,5,6")) {
                knowledgeTypeEntity.setSelect(true);
            } else {
                knowledgeTypeEntity.setSelect(false);
            }
        }
        knowledgeTypeEntity.setName("综合");
        knowledgeTypeEntity.setType("");
        typeEntityList.add(knowledgeTypeEntity);
        KnowledgeTypeEntity knowledgeTypeEntity2 = new KnowledgeTypeEntity();
        knowledgeTypeEntity2.setName("视频");
        knowledgeTypeEntity2.setType("2");
        if (Utils.isNull(resourceType)) {
            knowledgeTypeEntity2.setSelect(false);
        } else {
            if (resourceType.contains("2")) {
                knowledgeTypeEntity2.setSelect(true);
            } else {
                knowledgeTypeEntity2.setSelect(false);
            }
        }

        typeEntityList.add(knowledgeTypeEntity2);
        KnowledgeTypeEntity knowledgeTypeEntity3 = new KnowledgeTypeEntity();
        if (Utils.isNull(resourceType)) {
            knowledgeTypeEntity3.setSelect(false);
        } else {
            if (resourceType.contains("3")) {
                knowledgeTypeEntity3.setSelect(true);
            } else {
                knowledgeTypeEntity3.setSelect(false);
            }
        }
        knowledgeTypeEntity3.setName("小视频");
        knowledgeTypeEntity3.setType("3");
        typeEntityList.add(knowledgeTypeEntity3);
        KnowledgeTypeEntity knowledgeTypeEntity4 = new KnowledgeTypeEntity();
        if (Utils.isNull(resourceType)) {
            knowledgeTypeEntity4.setSelect(false);
        } else {
            if (resourceType.contains("1")) {
                knowledgeTypeEntity4.setSelect(true);
            } else {
                knowledgeTypeEntity4.setSelect(false);
            }
        }
        knowledgeTypeEntity4.setName("资料");
        knowledgeTypeEntity4.setType("1");
        typeEntityList.add(knowledgeTypeEntity4);
        KnowledgeTypeEntity knowledgeTypeEntity5 = new KnowledgeTypeEntity();
        if (Utils.isNull(resourceType)) {
            knowledgeTypeEntity5.setSelect(false);
        } else {
            if (resourceType.contains("5")) {
                knowledgeTypeEntity5.setSelect(true);
            } else {
                knowledgeTypeEntity5.setSelect(false);
            }
        }
        knowledgeTypeEntity5.setName("图文");
        knowledgeTypeEntity5.setType("5");
        typeEntityList.add(knowledgeTypeEntity5);
        KnowledgeTypeEntity knowledgeTypeEntity6 = new KnowledgeTypeEntity();
        if (Utils.isNull(resourceType)) {
            knowledgeTypeEntity6.setSelect(false);
        } else {
            if (resourceType.contains("6")) {
                knowledgeTypeEntity6.setSelect(true);
            } else {
                knowledgeTypeEntity6.setSelect(false);
            }
        }
        knowledgeTypeEntity6.setName("图片");
        knowledgeTypeEntity6.setType("6");
        typeEntityList.add(knowledgeTypeEntity6);
        rvType.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rvType.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)));
        typeAdapter = new TypeAdapter(R.layout.item_subject_choice, mContext, typeEntityList);
        rvType.setAdapter(typeAdapter);
        //文件夹
        folderRcv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        folderAdapter = new FolderAdapter(R.layout.item_knowledge_folder, this, folderList, nameList, level, catalogCustomType, catalogType, 0, levelOne, resourceType);
        folderRcv.setAdapter(folderAdapter);
        //文件
        fileRcv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        fileListAdapter = new JustOpenListAdapter(R.layout.item_knowledge_look, this, fileList, TAG + level);
        fileRcv.setAdapter(fileListAdapter);
        srlView.autoRefresh();
        registerBoradcastReceiver();
        checkUpdate();
        if(!Utils.isNull(catalogCustomType)||"0".equals(parentCode)){
            //自定义隐藏类型筛选   父级是自定义隐藏筛选
            llChoose.setVisibility(View.GONE);
        }
    }

    private void checkUpdate() {
        if ("-1".equals(catalogType)||"3".equals(parentCode)||"2".equals(parentCode)||"3001".equals(parentCode)) {
            //表面是知识库的自定义第二级，只有第三级才可以添加   个人文件和我的部门的第二级也不能添加   我的上传也不能传
            return;
        }
        Map<String, String> map = new HashMap<>();
//        （0：全局 1: 题库 2:视频 3:资料库 4：图库 5：图文）
        map.put("catalogCode", parentCode);
        map.put("catalogType", catalogType);
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.checkUpdate, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        folderAdapter.setPermissions(true);
                        llAdd.setVisibility(View.VISIBLE);
                    } else {
                        folderAdapter.setPermissions(false);
                        llAdd.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    private void getCatalogData() {
        resourceType = "";
        resourceName = "";
        if (typeEntityList.get(0).isSelect() || (typeEntityList.get(1).isSelect() && typeEntityList.get(2).isSelect() && typeEntityList.get(3).isSelect() && typeEntityList.get(4).isSelect() && typeEntityList.get(5).isSelect())) {
            resourceType = "1,2,3,5,6";
        } else if (!typeEntityList.get(1).isSelect() && !typeEntityList.get(2).isSelect() && !typeEntityList.get(3).isSelect() && !typeEntityList.get(4).isSelect() && !typeEntityList.get(5).isSelect()) {
            resourceType = "";
        } else {
            for (int i = 0; i < typeEntityList.size(); i++) {
                if (i >= 1 && typeEntityList.get(i).isSelect()) {
                    if (Utils.isNull(resourceType)) {
                        resourceType = resourceType + typeEntityList.get(i).getType();
                        resourceName = resourceName + typeEntityList.get(i).getName();
                    } else {
                        resourceType = resourceType + "," + typeEntityList.get(i).getType();
                        resourceName = resourceName + "、" + typeEntityList.get(i).getName();
                    }
                }
            }
        }
//        if(Utils.isNull(resourceType)||resourceType.equals("1,2,3,5,6")){
//            tvRight.setText("全部");
//            tvRight.setTextColor(Color.parseColor("#333333"));
//        }else{
//            tvRight.setText(resourceName);
//            tvRight.setTextColor(Color.parseColor("#333333"));
//        }
        folderAdapter.setResourceType(resourceType);
        Map<String, String> map = new HashMap<>();
        map.put("parentCode", parentCode);
        if (!Utils.isNull(catalogCustomType)) {
//            1资料库2视频3小视频5图文6图库
            map.put("catalogType", catalogCustomType);
            map.put("resourceType", catalogCustomType);
        }
        if (!Utils.isNull(resourceType)) {
            if (resourceType.equals("1,2,3,5,6")) {
            } else {
                map.put("resourceType", resourceType);
            }
        }
        //        catalogType 目录类型 1-小视频，2长视频 3资料库
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<FolderEntity>>>() {
        }.getType(), null, Urls.selectCatalogTreeZsk, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<FolderEntity>>() {
            @Override
            public void onSuccess(List<FolderEntity> data) {
                loadEnd();
                folderList.clear();
                folderAdapter.notifyDataSetChanged();
                if (data != null && data.size() > 0) {
                    folderList.addAll(data);
                    folderAdapter.notifyDataSetChanged();
//                    for (int i = 0; i < data.size(); i++) {
//                        if (i == 0) {
//                            folderName = folderName + data.get(i).getName();
//                        } else {
//                            folderName = folderName + "," + data.get(i).getName();
//                        }
//                    }
//                    tvFolderTopName.setText(folderName);
                }
                llFolderTop.setVisibility(View.GONE);
                folderOpen = false;
                tvFolderArrow.setVisibility(View.INVISIBLE);
                ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                if (folderList.size() == 0) {
                    folderRcv.setVisibility(View.GONE);
                    llFolderAll.setVisibility(View.GONE);
                    spaceView.setVisibility(View.GONE);
                } else {
                    folderRcv.setVisibility(View.VISIBLE);
                    llFolderAll.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                    if (fileList.size() > 0) {
                        spaceView.setVisibility(View.VISIBLE);
                    } else {
                        spaceView.setVisibility(View.GONE);
                    }
                }
                if (folderList.size() > 0) {
                    tvFolderTopName.setText("共" + folderList.size() + "个文件夹");
                    tvFolderName.setText("文件夹");
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getFileList() {
        resourceType = "";
        if (typeEntityList.get(0).isSelect() || (typeEntityList.get(1).isSelect() && typeEntityList.get(2).isSelect() && typeEntityList.get(3).isSelect() && typeEntityList.get(4).isSelect() && typeEntityList.get(5).isSelect())) {
            resourceType = "1,2,3,5,6";
        } else if (!typeEntityList.get(1).isSelect() && !typeEntityList.get(2).isSelect() && !typeEntityList.get(3).isSelect() && !typeEntityList.get(4).isSelect() && !typeEntityList.get(5).isSelect()) {
            resourceType = "";
        } else {
            for (int i = 0; i < typeEntityList.size(); i++) {
                if (i >= 1 && typeEntityList.get(i).isSelect()) {
                    if (Utils.isNull(resourceType)) {
                        resourceType = resourceType + typeEntityList.get(i).getType();
                    } else {
                        resourceType = resourceType + "," + typeEntityList.get(i).getType();

                    }
                }
            }
        }
        folderAdapter.setResourceType(resourceType);
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        if (!Utils.isNull(resourceType)) {
            if (resourceType.equals("1,2,3,5,6")) {
            } else {
                map.put("resourceType", resourceType);
            }
        }
        if (!Utils.isNull(catalogCustomType)) {
//            1资料库2视频3小视频5图文6图库  自定义的时候限制类型
            map.put("resourceType", catalogCustomType);
        }
        map.put("parentCode", parentCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<FileEntity>>() {
        }.getType(), null, Urls.getFileByParentCode, SignUtils2.makeSignStr(map), false, new ObserverCallback<FileEntity>() {
            @Override
            public void onSuccess(FileEntity data) {
                loadEnd();
                if (currentPage == 1) {
                    fileList.clear();
                    fileListAdapter.notifyDataSetChanged();
                }
                llFileTop.setVisibility(View.GONE);
                fileOpen = false;
                tvFileArrow.setVisibility(View.INVISIBLE);
                ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                if (data != null && data.getList().size() > 0) {
                    fileList.addAll(data.getList());
                    fileListAdapter.notifyDataSetChanged();
                    fileRcv.setVisibility(View.VISIBLE);
                    llFileAll.setVisibility(View.VISIBLE);
                    if (folderList.size() > 0) {
                        spaceView.setVisibility(View.VISIBLE);
                    } else {
                        spaceView.setVisibility(View.GONE);
                    }
                    llNone.setVisibility(View.GONE);
//                    if (currentPage == 1) {
//                        for (int i = 0; i < data.getList().size(); i++) {
//                            if (i == 0) {
//                                fileName = fileName + data.getList().get(i).getResourceName();
//                            } else {
//                                fileName = fileName + "," + data.getList().get(i).getResourceName();
//                            }
//                            tvFileTopName.setText(fileName);
//                        }
//                    }
                } else {
                    isEnd = true;
                    if (fileList.size() == 0) {
                        spaceView.setVisibility(View.GONE);
                        fileRcv.setVisibility(View.GONE);
                        llFileAll.setVisibility(View.GONE);
                        if (folderList.size() == 0) {
                            llNone.setVisibility(View.VISIBLE);
                        } else {
                            llNone.setVisibility(View.GONE);
                        }
                    } else {
                        if (folderList.size() > 0) {
                            spaceView.setVisibility(View.VISIBLE);
                        } else {
                            spaceView.setVisibility(View.GONE);
                        }
                        fileRcv.setVisibility(View.VISIBLE);
                        llFileAll.setVisibility(View.VISIBLE);
                        llNone.setVisibility(View.GONE);
                    }
                }
                if (fileList.size() > 0) {
                    tvFileTopName.setText("共" + data.getTotalNum() + "个文件");
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh();
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore();
    }

    class TypeAdapter extends BaseQuickAdapter<KnowledgeTypeEntity, BaseViewHolderEx> {
        private Context context;

        public TypeAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<KnowledgeTypeEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, KnowledgeTypeEntity item) {
            ImageView ivStatus = helper.getView(R.id.ivStatus);
            TextView tvTiltle = helper.getView(R.id.tvTiltle);
            tvTiltle.setText(item.getName());
            if (item.isSelect()) {
                ivStatus.setSelected(true);
            } else {
                ivStatus.setSelected(false);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isSelect()) {
                        typeEntityList.get(helper.getItemPosition()).setSelect(false);
                        typeEntityList.get(0).setSelect(false);
                    } else {
                        typeEntityList.get(helper.getItemPosition()).setSelect(true);
                        if (helper.getItemPosition() > 0) {
                            if (typeEntityList.get(1).isSelect() && typeEntityList.get(2).isSelect() && typeEntityList.get(3).isSelect() && typeEntityList.get(4).isSelect() && typeEntityList.get(5).isSelect()) {
                                typeEntityList.get(0).setSelect(true);
                            } else {
                                typeEntityList.get(0).setSelect(false);
                            }
                        } else {
                            typeEntityList.get(1).setSelect(true);
                            typeEntityList.get(2).setSelect(true);
                            typeEntityList.get(3).setSelect(true);
                            typeEntityList.get(4).setSelect(true);
                            typeEntityList.get(5).setSelect(true);
                        }
                    }
                    typeAdapter.notifyDataSetChanged();
                    srlView.autoRefresh();
                    rlType.setVisibility(View.GONE);
//                    ivRight.setBackgroundResource(R.drawable.arrow_down_all);
                }
            });
        }
    }

    class TitleAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Activity context;

        public TitleAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String entity) {
            TextView tvItemTitle = helper.getView(R.id.tvTitle);
            ImageView ivArrow = helper.getView(R.id.ivArrow);
            tvItemTitle.setText(entity);
            if (helper.getItemPosition() > 0) {
                ivArrow.setVisibility(View.VISIBLE);
            } else {
                ivArrow.setVisibility(View.GONE);
            }
            if (helper.getItemPosition() == nameList.size() - 1) {
                tvItemTitle.setTextColor(Color.parseColor("#333333"));
            } else {
                tvItemTitle.setTextColor(Color.parseColor("#8a8a8a"));
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }

                    HashMap<String, String> map = new HashMap<>();
                    if (helper.getItemPosition() == 0) {
                        if (levelOne != null) {
                            Intent intent = new Intent(context, KnowledgeBaseSecondActivity.class);
                            intent.putExtra("parentCode", levelOne.getCode());
                            intent.putExtra("folderNum", levelOne.getFolderNum());
                            intent.putExtra("levelOne", levelOne);
                            intent.putExtra("resourceType", resourceType);
                            intent.putExtra("level", 1);
                            ArrayList<String> nameList = new ArrayList<>();//组织排列
                            nameList.add(levelOne.getName());
                            intent.putStringArrayListExtra("nameList", nameList);
                            startActivity(intent);
                        }
                        map.put("KnowledgeBaseSecond", "0");
                        EventBus.getDefault().post(new MyEvent(map));
                    } else {
                        map.put("KnowledgeBaseSecond", (helper.getItemPosition() + 1) + "");
                        EventBus.getDefault().post(new MyEvent(map));
                    }

                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("KnowledgeBaseSecond")) {
                int oldLevel = Utils.changeNumber(map.get("KnowledgeBaseSecond"));
                if (level > oldLevel) {
                    finish();
                }
            }else  if(map.containsKey("DocumentPreview_error")){
                for (int i = 0; i < fileList.size(); i++) {
                    if ("1".equals(fileList.get(i).getResourceType())) {
                        if (fileList.get(i).getResourceId().equals(map.get("DocumentPreview_error"))) {
                            fileList.get(i).setError(true);
                        }
                    }

                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("RefreshDirectory")) {
                    srlView.autoRefresh();
                }
            }
        }
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < fileList.size(); i++) {
                    if ("1".equals(fileList.get(i).getResourceType())) {
                        if (fileList.get(i).getResourceId().equals(recevierDataCode)) {
                            if (!fileList.get(i).isOpen()) {
                                if (encryptStatus) {
                                    fileList.get(i).setOpen(true);
                                }
                                dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                            }

                        }
                    }

                }

            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);

            }
        } else {
            if (percent > 0 && percent < 100) {
                if (fileListAdapter != null) {
                    fileList.get(position).setProgress(percent);
                    fileListAdapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (fileListAdapter != null) {
                    fileList.get(position).setProgress(100);
                    fileListAdapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(KnowledgeBaseSecondActivity.this, fileUrl, fileName, recevierDataCode, TAG + level);
                        }
                    }.start();
                }


            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(TAG + level);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private void requestCamera(int type) {
        if (type == 2) {
            XXPermissions.with(this)
                    .permission(Permission.CAMERA)
                    .permission(Permission.Group.STORAGE)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> granted, boolean all) {
                            if (all) {
                                PictureSelector.create(KnowledgeBaseSecondActivity.this)
                                        .openGallery(SelectMimeType.ofVideo())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxVideoSelectNum(1)
                                        .setMaxSelectNum(1)
                                        .setSelectionMode(SelectModeConfig.SINGLE)//单选
                                        .isPreviewVideo(true)//是否支持预览视频
                                        .setSelectMinFileSize(50)//过滤最小文件50k
                                        .setFilterVideoMaxSecond(600)//过滤最大视频选择600s
                                        .setRecordVideoMaxSecond(30)//过滤录制最大30s
                                        .isFilterSizeDuration(true)//是否过滤图片或音视频大小时长为0的资源
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.REQUEST_CAMERA);
                            }
                        }

                        @Override
                        public void onDenied(List<String> denied, boolean quick) {
                            PermissionUtils.errorPermission(mContext, denied, quick);
                        }
                    });
        } else {
            XXPermissions.with(this)
                    .permission(Permission.Group.STORAGE)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> granted, boolean all) {
                            if (all) {
                                if (type == 1) {
                                    FilePicker
                                            .from(KnowledgeBaseSecondActivity.this)
                                            .chooseForMimeType()
                                            .setMaxCount(9)
                                            .setFileTypes("pdf", "doc", "ppt", "xls")
                                            .requestCode(REQUEST_CODE_CHOOSE)
                                            .start();
                                } else if (type == 3) {
                                    PictureSelector.create(KnowledgeBaseSecondActivity.this)
                                            .openGallery(SelectMimeType.ofImage())
                                            .isDisplayCamera(true)//是否显示相机入口
                                            .setMaxSelectNum(9)
                                            .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                            .isPreviewImage(true)//是否支持预览图片
                                            .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                            .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                            .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                            .forResult(PictureConfig.CHOOSE_REQUEST);
                                }
                            }
                        }

                        @Override
                        public void onDenied(List<String> denied, boolean quick) {
                            PermissionUtils.errorPermission(mContext, denied, quick);
                        }
                    });
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                ArrayList<String> imgList = new ArrayList<>();
                for (int i = 0; i < selectList.size(); i++) {
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    imgList.add(url);
                    KLog.i("Android Q 特有Path::" + url);
                }
                if (imgList.size() > 0) {
                    Intent intent = new Intent(KnowledgeBaseSecondActivity.this, PublishGalleryActivity.class);
                    intent.putStringArrayListExtra("imgUrls", imgList);
                    intent.putExtra("directoryName", nameList.get(nameList.size() - 1));
                    intent.putExtra("directoryCode", parentCode);
                    startActivity(intent);
                }
            }
            if (requestCode == PictureConfig.REQUEST_CAMERA) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                Intent intent = new Intent(KnowledgeBaseSecondActivity.this, PublishVedioActivity.class);
                String url = "";
                if (selectList.get(0).getPath().contains("content://")) {
                    Uri uri = Uri.parse(selectList.get(0).getPath());
                    url = PathUtil.getPath(this, uri);
                } else {
                    url = selectList.get(0).getPath();
                }
                intent.putExtra("fileUrl", url);
                if(nameList.size()>0){
                    intent.putExtra("directoryName", nameList.get(nameList.size() - 1));
                    intent.putExtra("directoryCode", parentCode);
                }
                startActivity(intent);
            }
            if (requestCode == REQUEST_CODE_CHOOSE) {
                //文档选择
                ArrayList<EssFile> essFileList = data.getParcelableArrayListExtra(Const.EXTRA_RESULT_SELECTION);
                ArrayList< UploadEntity> docList = new ArrayList<>();
                if (essFileList.size() != 0) {
                    for (int i = 0; i < essFileList.size(); i++) {
                        UploadEntity uploadEntity = new  UploadEntity();
                        UploadEntity.DataBaseBean docunmentEntity= new UploadEntity.DataBaseBean();
                        docunmentEntity.setDataTitle(essFileList.get(i).getName());
                        docunmentEntity.setParentCode(parentCode);
                        docunmentEntity.setParentName(nameList.get(nameList.size() - 1));
                        docunmentEntity.setDataPath(nameList.get(nameList.size() - 1));
                        docunmentEntity.setLocalDataPath(essFileList.get(i).getAbsolutePath());
                        docunmentEntity.setFileType(FileUtils.getExtensionType(essFileList.get(i).getName()).toLowerCase());
                        docunmentEntity.setProvideEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
                        docunmentEntity.setProvideEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
                        docunmentEntity.setUploadTime(Utils.getCurrentTime2());
                        docunmentEntity.setShareFlag("1");
                        docunmentEntity.setOriginal("1");
                        docunmentEntity.setDataSize(FileSizeUtil.getAutoFileOrFilesSize((essFileList.get(i).getFile())));
                        uploadEntity.setDataBase(docunmentEntity);
                        uploadEntity.setUploadStatus(1);
                        uploadEntity.setResourceType("1");
                        uploadEntity.setProvideEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
                        uploadEntity.setUploadTitle(essFileList.get(i).getName());
                        uploadEntity.setUploadTag(Utils.getCurrentTime2()+"-"+i);
                        docList.add(uploadEntity);
                    }
                    Intent intent = new Intent(KnowledgeBaseSecondActivity.this, UploadFileService.class);
                    Bundle bundle = new Bundle();
                    //须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
                    ArrayList bundlelist = new ArrayList();
                    bundlelist.add(docList);
                    bundle.putParcelableArrayList("data", bundlelist);
                    intent.putExtras(bundle);
                    intent.putExtra("resourceType","1");
                    startService(intent);
                } else {
                    KLog.i("essFileList.size() == 0");
                }
            }
        }
    }

    @OnClick({R.id.title_back, R.id.llAdd, R.id.llChoose, R.id.rlType, R.id.llFileArrow, R.id.llFolderArrow, R.id.llFolderTop, R.id.llFileTop})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.llAdd:
                int catalogTypeInt = Utils.changeNumber(catalogType);
                String dialogType = "";
                if (catalogTypeInt > 0) {
                    //限制第二层只能新建文件夹，不能新增
                    if (level == 2) {
                        dialogType = "99";
                    } else {
                        if(catalogCustomType.equals("2")){
                            //长视频不能传
                            dialogType = "99";
                        }else{
                            dialogType = catalogType;
                        }

                    }
                } else if (catalogTypeInt == 0) {
                    if (level == 1) {
                        dialogType = "99";
                    } else {
                        dialogType = catalogType;
                    }
                } else {
                    dialogType = catalogType;
                }
                new UploadBottomDialog(mContext, 0, dialogType, new HomeBottomDialogListener() {
                    @Override
                    public void onListItemClick(int position) {
                        if (position == 0) {
//                          （0：全局 1: 题库 2:视频 3:资料库 4：图库 5：图文）
                            Intent intent = new Intent(mContext, BuildDirectoryActivity.class);
                            intent.putExtra("catalogType", catalogType);
                            if(!Utils.isNull(catalogCustomType)){
                                //单独处理自定义下的数据
                               if(level==2){
                                   intent.putExtra("parentCode", "0");
                               }else{
                                   intent.putExtra("parentCode", parentCode);
                               }
                            }else{
                                intent.putExtra("parentCode", parentCode);
                            }
                            intent.putStringArrayListExtra("nameList", nameList);
                            mContext.startActivity(intent);
                        } else if (position == 1) {
                            requestCamera(1);
                        } else if (position == 2) {
                            requestCamera(2);
                        } else if (position == 3) {
                            requestCamera(3);
                        } else if (position == 4) {
                            Intent intent = new Intent(mContext, PublishTuwensActivity.class);
                            intent.putExtra("directoryName", nameList.get(nameList.size() - 1));
                            intent.putExtra("directoryCode", parentCode);
                            mContext.startActivity(intent);
                        }
                    }
                }).show();
                break;
            case R.id.llChoose:
                if (rlType.getVisibility() == View.VISIBLE) {
                    rlType.setVisibility(View.GONE);
//                    ivRight.setBackgroundResource(R.drawable.arrow_down_all);
                } else {
                    rlType.setVisibility(View.VISIBLE);
//                    ivRight.setBackgroundResource(R.drawable.arrow_up_all);
                }
                break;
            case R.id.rlType:
                rlType.setVisibility(View.GONE);
//                ivRight.setBackgroundResource(R.drawable.arrow_down_all);
                break;
            case R.id.llFolderArrow:
            case R.id.llFolderTop:
                if (folderOpen) {
                    folderOpen = false;
                    tvFolderArrow.setVisibility(View.INVISIBLE);
                    ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                    llFolderTop.setVisibility(View.GONE);
                    folderRcv.setVisibility(View.VISIBLE);
                } else {
                    folderOpen = true;
                    tvFolderArrow.setVisibility(View.VISIBLE);
                    ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_up_18);
                    llFolderTop.setVisibility(View.VISIBLE);
                    folderRcv.setVisibility(View.GONE);
                }
                break;
            case R.id.llFileArrow:
            case R.id.llFileTop:
                if (fileOpen) {
                    fileOpen = false;
                    tvFileArrow.setVisibility(View.INVISIBLE);
                    ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                    llFileTop.setVisibility(View.GONE);
                    fileRcv.setVisibility(View.VISIBLE);
                } else {
                    fileOpen = true;
                    tvFileArrow.setVisibility(View.VISIBLE);
                    ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_up_18);
                    llFileTop.setVisibility(View.VISIBLE);
                    fileRcv.setVisibility(View.GONE);
                }
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
        EventBus.getDefault().unregister(this);
    }
}
